
import { useState } from 'react';
import { useEffect } from 'react';

import { ConnectorDataSource, DataSource, ConnectorDatabaseType as DatabaseType } from '@/services';
import { mysqlColumns, mysqlTableRequest, mysqlAlterTable } from './mysql';
import { sqliteColumns, sqliteTableRequest, sqliteAlterTable } from './sqlite';
import { BaseTableStructure } from './table-structure';
import { EditableTableColumn } from '@/components';

export const TableStructure = (props: { dataSource: ConnectorDataSource, table: string }) => {

    const [columns, setColumns] = useState<EditableTableColumn[]>([]);

    useEffect(() => {
        let dtype = props.dataSource.database_type;

        if (dtype === 'mysql') {
            mysqlColumns().then((columns) => {
                setColumns(columns);
            })
        } else if (dtype === 'sqlite') {
            sqliteColumns().then((columns) => {
                setColumns(columns);
            })
        }
    }, [props.dataSource, props.table]);

    return (
        <BaseTableStructure
            dataSource={props.dataSource}
            table={props.table}
            columns={columns}
            request={async () => {
                let dtype = props.dataSource.database_type;

                let data = [];
                if (dtype === 'mysql') {
                    data = await mysqlTableRequest(props.dataSource, props.table);
                } else if (dtype === 'sqlite') {
                    data = await sqliteTableRequest(props.dataSource, props.table);
                }
                console.log('structure:', data, dtype);
                return data;
            }}
            onSave={async (rowIndex: number, columnId: string, value: unknown, data: any) => {
                let dtype = props.dataSource.database_type;
                if (dtype === 'mysql') {
                    data = await mysqlAlterTable(props.dataSource, props.table, rowIndex, columnId, value, data);
                } else if (dtype === 'sqlite') {
                    data = await sqliteAlterTable(props.dataSource, props.table, rowIndex, columnId, value, data);
                }
            }}>
        </BaseTableStructure>
    );
}